package com.example.sm2.swing;

import com.example.sm2.cipher.sm2.SM2Utils2;
import org.bouncycastle.util.encoders.Hex;

import javax.swing.*;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.util.Base64;

public class Frame extends JFrame {

    JButton createPrivateKeyBt;
    JButton openPathBt;
    JButton copyPrivateKeyBt;
    JButton copyPublicKeyBt;

    ButtonGroup buttGroup;

    JPanel formatPanel;
    JPanel buttonPanel;
    JPanel privateKeyPanel;
    JPanel hexPrivateKeyPanel;
    JPanel copyPrivatePanel;
    JPanel publicKeyPanel;
    JPanel hexPublicKeyPanel;
    JPanel copyPublicPanel;

    JLabel formatLabel;
    JLabel privateKeyLabel;
    JLabel hexPrivateKeyLabel;
    JLabel publicKeyLabel;
    JLabel hexPublicKeyLabel;
    JLabel copyPrivateKeySucc;
    JLabel copyPublicKeySucc;

    JTextArea privateKeyArea;
    JTextArea hexPrivateKeyArea;
    JTextArea publicKeyArea;
    JTextArea hexPublicKeyArea;

    public Frame() {
        setTitle("SM2密钥工具(v1.0)");
        setLayout(new FlowLayout());
        //密钥格式行
        formatPanel=new JPanel();
        formatLabel = new JLabel("密钥格式  base64      base16                     ");
        buttGroup = new ButtonGroup();
        formatPanel.add(formatLabel);
        formatPanel.add(new JLabel("                                                                                                                                                                              "));
        //按钮：生成密钥 and 打开密钥文件路径
        buttonPanel=new JPanel();
        createPrivateKeyBt=new JButton("生成密钥");
        openPathBt=new JButton("打开密钥文件路径");
        buttonPanel.add(createPrivateKeyBt);
        buttonPanel.add(openPathBt);
        buttonPanel.add(new JLabel("                                                                                                                                    "));
        //应用私钥行
        privateKeyPanel=new JPanel();
        privateKeyLabel = new JLabel("应用私钥base64");
        privateKeyArea=new JTextArea("",3,80);
        privateKeyArea.setEditable(false);
        privateKeyArea.setLineWrap(true);
        privateKeyPanel.add(privateKeyLabel);
        privateKeyPanel.add(privateKeyArea);
        //16进制的应用私钥行
        hexPrivateKeyPanel = new JPanel();
        hexPrivateKeyLabel = new JLabel("应用私钥base16");
        hexPrivateKeyArea = new JTextArea("",3,80);
        hexPrivateKeyArea.setEditable(false);
        hexPrivateKeyArea.setLineWrap(true);
        hexPrivateKeyPanel.add(hexPrivateKeyLabel);
        hexPrivateKeyPanel.add(hexPrivateKeyArea);
        //复制私钥按钮
        copyPrivatePanel=new JPanel();
        copyPrivateKeyBt=new JButton("复制base64私钥");
        copyPrivateKeySucc = new JLabel("");
        copyPrivatePanel.add(copyPrivateKeyBt);
        copyPrivatePanel.add(copyPrivateKeySucc);
        //应用公钥行
        publicKeyPanel=new JPanel();
        publicKeyLabel = new JLabel("应用公钥base64");
        publicKeyArea=new JTextArea("",3,80);
        publicKeyArea.setEditable(false);
        publicKeyArea.setLineWrap(true);
        publicKeyPanel.add(publicKeyLabel);
        publicKeyPanel.add(publicKeyArea);
        //16进制的应用公钥行
        hexPublicKeyPanel = new JPanel();
        hexPublicKeyLabel = new JLabel("应用公钥base16");
        hexPublicKeyArea = new JTextArea("",3,80);
        hexPublicKeyArea.setEditable(false);
        hexPublicKeyArea.setLineWrap(true);
        hexPublicKeyPanel.add(hexPublicKeyLabel);
        hexPublicKeyPanel.add(hexPublicKeyArea);
        //复制公钥按钮
        copyPublicPanel=new JPanel();
        copyPublicKeyBt=new JButton("复制base64公钥");
        copyPublicKeySucc = new JLabel("");
        copyPublicPanel.add(copyPublicKeyBt);
        copyPublicPanel.add(copyPublicKeySucc);
        //添加panel
        add(formatPanel);
        add(buttonPanel);
        add(privateKeyPanel);
        add(hexPrivateKeyPanel);
        add(copyPrivatePanel);
        add(publicKeyPanel);
        add(hexPublicKeyPanel);
        add(copyPublicPanel);
        setBounds(300,200,1000,480);
        setIconImage(new ImageIcon(this.getClass().getResource("/logo.png")).getImage());
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setResizable(true);
    }

    public static void main(String[] args) {
        Frame frame = new Frame();
        frame.addActionListener();
    }

    //监听按钮
    private void addActionListener(){
        createPrivateKeyBt.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                copyPublicKeySucc.setText("");
                copyPrivateKeySucc.setText("");
                //获取公钥密钥对
                String[] keypairs = null;
                try {
                    keypairs = SM2Utils2.generateSmKey();
                } catch (Exception exception) {
                    exception.printStackTrace();
                }
                //展示asn.1格式的base64密钥
                privateKeyArea.setText(keypairs[1]);
                publicKeyArea.setText(keypairs[0]);
                //展示base16密钥
                byte[] priBase64 = Base64.getDecoder().decode(keypairs[1]);
                hexPrivateKeyArea.setText(Hex.toHexString(priBase64));
                byte[] pubBase64 = Base64.getDecoder().decode(keypairs[0]);
                hexPublicKeyArea.setText(Hex.toHexString(pubBase64));
                //存放密钥对
                OutputStreamWriter outputStreamWriter = null;
                try{
                    outputStreamWriter = new OutputStreamWriter(
                            new FileOutputStream(new File(System.getProperty("user.dir")+"\\private_key.txt")));
                    outputStreamWriter.append(keypairs[1]);
                    outputStreamWriter.flush();
                    outputStreamWriter = new OutputStreamWriter(
                            new FileOutputStream(new File(System.getProperty("user.dir")+"\\public_key.txt")));
                    outputStreamWriter.append(keypairs[0]);
                    outputStreamWriter.flush();
                } catch (FileNotFoundException fileNotFoundException) {
                    fileNotFoundException.printStackTrace();
                } catch (IOException ioException) {
                    ioException.printStackTrace();
                } finally {
                    try {
                        outputStreamWriter.close();
                    } catch (IOException ioException) {
                        ioException.printStackTrace();
                    }
                }
            }
        });

        openPathBt.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    Desktop.getDesktop().open(new File(System.getProperty("user.dir")));
                } catch (IOException ioException) {
                    ioException.printStackTrace();
                }
            }
        });

        copyPrivateKeyBt.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                Document document = privateKeyArea.getDocument();
                try {
                    String text = document.getText(0, document.getLength());
                    if(!"".equals(text)){
                        Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
                        Transferable tText = new StringSelection(text);
                        clipboard.setContents(tText, null);
                        copyPrivateKeySucc.setText("复制成功");
                    }
                } catch (BadLocationException badLocationException) {
                    badLocationException.printStackTrace();
                }
            }
        });

        copyPublicKeyBt.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                Document document = publicKeyArea.getDocument();
                try {
                    String text = document.getText(0, document.getLength());
                    if(!"".equals(text)){
                        Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
                        Transferable tText = new StringSelection(text);
                        clipboard.setContents(tText, null);
                        copyPublicKeySucc.setText("复制成功");
                    }
                } catch (BadLocationException badLocationException) {
                    badLocationException.printStackTrace();
                }
            }
        });
    }
}
